<template>
	<view class="commonpopup">
		<u-popup :show="showPopup" mode="center" @close="closeCommonPopup()" @cancel="closeCommonPopup()"
			@open="openCommonPopup()" :closeOnClickOverlay="true">
			<view class="commonPopInfo" v-if="globalConfig && commonPopupInfo">
				<view class="label" :style="globalConfig.globalStyle.popupLabelStyle">
					{{commonPopupInfo.popupInfo.label}}</view>
				<view class="body">
					<text class="textarea" space="emsp"
						v-if="commonPopupInfo.popupInfo.text">{{commonPopupInfo.popupInfo.text}} </text>
					<view class="checkbox" v-if="commonPopupInfo.popupInfo.wait">
						请先仔细阅读上文，还剩{{commonPopupInfo.popupInfo.wait}}秒
					</view>
					<view class="checkbox"
						v-if="!commonPopupInfo.popupInfo.wait && commonPopupInfo.popupInfo.showConfirm">
						<u-checkbox-group v-model="commonPopupInfo.popupInfo.comfirm" placement="column"
							@change="commonPopupCheckboxChanged">
							<u-checkbox :customStyle="{marginBottom: '8px'}" shape="circle" name="readbeforeConfirm"
								:label="commonPopupInfo.popupInfo.confirmText">
							</u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="formPage" v-if="formItems && model">
						<u--form labelPosition="left" :model="model" ref="form1" reef="form1">
							<view v-for="(item, index) in formItems" :key="index" class="fieldItem"
								:class="{candelete: item.candelete}" v-show="!item.hide">
								<view v-if="item.type == 'text'"
									:class="[item.prop, {address: item.address, hasBtn: item.prop == 'dxyzNo' || item.autho}]">
									<u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="80"
										@click="openPicker(item)">
										<u--input v-model="model[item.prop]" :placeholder="item.placeholder"
											border="none" :readonly="item.readonly"></u--input>
										<view class="getcode" v-if="item.prop == 'dxyzNo'">
											<u-button @tap="getCode" type="success" :disabled="validateBtnDisabled"
												size="small">{{ validateTips }}</u-button>
										</view>

										<view class="getcode" v-if="item.autho == 'faceValidate'">
											<u-button @tap="startFaceValidate(item)" type="success"
												size="small">点击认证</u-button>
										</view>
										<view class="getcode" v-if="item.autho == 'phone'">
											<u-button open-type="getPhoneNumber"
												@getphonenumber="getPhoneNumber($event, item)" type="success"
												size="small">授权手机号</u-button>
										</view>
									</u-form-item>
								</view>
								<view v-else-if="item.type == 'checkbox'" v-show="!item.hide"
									:class="[item.prop]">
									<u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="80">
										<view class="options">
											<view class="option" v-for="(op, opindex) in item.options" :key="opindex" :class="{ active: op.active }" @click="optionChecked(item, opindex)">
												{{ op.name }}
											</view>
										</view>
									</u-form-item>
								</view>

							</view>
						</u--form>
					</view>
					<view class="confirmBtn">
						<u-button type="primary" @click="submit()"
							:disabled="commonPopupInfo.popupInfo.wait || commonPopupInfo.popupInfo.showConfirm && !commonPopupInfo.popupInfo.confirm">
							{{commonPopupInfo.popupInfo.confirmBtnText || '确定'}}</u-button>
					</view>
					<u-code :seconds="30" ref="uCode" reef="uCode" @change="codeChange" change-text="XS获取"
						@start="validateBtnDisabled = true" @end="validateBtnDisabled = false"></u-code>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {mapState,mapMutations} from 'vuex';
	import formMixins from '@/utils/formMixins.js'
	import WXBizDataCrypt from '@/utils/WXBizDataCrypt.js'
    import sceneMixins from '@/utils/sceneMixins.js';
	export default {
		mixins: [formMixins, sceneMixins],
		data() {
			return {
				showPopup: false,
				commonPopupInfo: '',
				firstShow: true
			};
		},
		mounted() {
			uni.login({
				provider: 'weixin',
				success: function (res) {
					console.log(res);
				}
			});
			var vm = this;
			vm.doWxLogin().then(res => {
				vm.openId = res.openId;
			});
            vm.waitVariable('globalConfig').then(() => {
                vm.$nextTick(() => {
					vm.commonPopupInfo = {
						popupInfo: JSON.parse(JSON.stringify(vm.globalConfig.registerForm))
					};
					vm.formItems = JSON.parse(JSON.stringify(vm.commonPopupInfo.popupInfo.form));
				})
            })
		},
		computed: {
			...mapState(['globalConfig'])
		},
		options: {
			styleIsolation: 'shared'
		},
		methods: {
			...mapMutations(['doLogin']),
			submit: function () {
				var vm = this;
				console.log(this.model);
				var form1 = vm.getRefCmp('form1');
				form1.validate().then(() => {
					var model = JSON.parse(JSON.stringify(vm.model));
					model.openId = vm.openId;
					var postUrl = vm.commonPopupInfo.popupInfo.loginApi;
					vm.getAndLoad('保存', postUrl + vm.$Util.stringify(model), function(res) {
						uni.hideLoading();
						if (res.code == 0) {
							uni.$u.toast('注册成功！');
							if (model.faceValidate) {
								vm.model.rz = true;
							}
							vm.doLogin(JSON.parse(JSON.stringify(vm.model)));
							vm.closeCommonPopup();
							vm.$emit('onlogin');
						} else {
							uni.$u.toast(res.msg || '注册失败');
						}
					});
				});
			},
			closeCommonPopup: function() {
				this.showPopup = false;
			},
			openCommonPopup: function() {
				var vm = this;
				this.showPopup = true;
				if (vm.commonPopupInfo.popupInfo.wait) {
					if (process.env.NODE_ENV == 'development') {
						vm.commonPopupInfo.popupInfo.wait = 3;
					}
					global.beforeWaitTo = setInterval(() => {
						if (vm.commonPopupInfo.popupInfo.wait) {
							vm.commonPopupInfo.popupInfo.wait--
						} else {
							clearInterval(global.beforeWaitTo);
						}
					}, 1000);
				}
				if (this.firstShow) {
					vm.formItems.forEach(n => {
						if (n.type == 'checkbox') {
							if (!n.options.map) {
								n.options = n.options.split('$').map((m, i) => {
									return {
										name: m.split(':')[1],
										active: !i,
										value: m.split(':')[0],
									};
								})
							} else {
								n.options = n.options.map((o, i) => {
									return { name: o, active: !i };
								});
							}
						}
					});
					vm.$nextTick(() => {
						vm.generateModelAndRules();
					});
					this.firstShow = false;
				}
			},
			getPhoneNumber: function(e, item) {
				var vm = this;
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					this.doWxLogin(true).then(res => {
						var pc = new WXBizDataCrypt(vm.globalConfig.appId, res.session_key);
						var phone = pc.decryptData(e.detail.encryptedData, e.detail.iv);
						vm.model[item.prop] = phone.phoneNumber;
					});
				} else {
					console.log('用户点击了拒绝');
				}
			},
			startFaceValidate: function (item) {
				var vm = this;
				var form1 = vm.getRefCmp('form1')
				form1.validateField(item.getProp[0], function(r1) {
					form1.validateField(item.getProp[1], function(r2) {
						if (!r1.length && !r2.length) { 
							wx.startFacialRecognitionVerify({
								name: vm.model[item.getProp[1]],
								idCardNumber: vm.model[item.getProp[0]],
								complete: function (res) {
									if (res.errCode == 0) {
										item.autho = '';
										vm.$set(vm.model, item.prop, '认证已通过');
										vm.formItems.find(n => n.prop == item.getProp[1]).readonly = true;
										vm.formItems.find(n => n.prop == item.getProp[0]).readonly = true;
									}
								}
							})
						}
					});
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.commonpopup {
		/deep/ .u-popup__content {
			background: transparent;
			border-radius: 20rpx;
		}

	}

	.commonPopInfo {
		width: 650rpx;

		>.label {
			height: 90rpx;
			line-height: 90rpx;
			text-indent: 30rpx;
		}

		.textarea {
			max-height: 700rpx;
			overflow-y: scroll;
			font-size: 26rpx;
			padding: 10rpx 30rpx;
			display: block;
		}

		.checkbox {
			padding: 10px 20rpx 0;
			zoom: 0.9;
		}

		.confirmBtn {
			padding: 0 30rpx 20rpx;
		}

		.body {
			background: #fff;
			border-radius: 0 0 20rpx 20rpx;
			overflow: hidden;
		}
	}

	.formPage {
		margin: 20rpx 0;
		width: 100%;
    	min-height: 300rpx;
		.fieldItem {
			position: relative;

			&.candelete {
				padding-top: 40rpx;
				background: #fff;
			}

			.delete-btn {
				position: absolute;
				right: 10rpx;
				top: 5rpx;
			}
		}

		/deep/ {
			.u-form-item {
				background: #fff;
				padding: 0 20rpx 0 30rpx;
			}

			.uni-input-input {
				text-align: right !important;
				font-size: 28rpx !important;
			}

			.u-input {
				background: transparent !important;
			}

			.u-form-item__body__right__message {
				text-align: right;
			}

			.u-upload__wrap {
				margin-left: auto;
			}

			.uni-input-placeholder {
				text-align: right !important;
				font-size: 28rpx !important;
			}

			.u-form-item__body__left__content__label {
				font-size: 28rpx;
			}

			.u-input__content__field-wrapper__field {
				text-align: right !important;
				font-size: 28rpx !important;
			}

			.u-form-item__body__right__content__slot {
				display: flex;
				flex-direction: row;

				region-picker {
					width: 100%;
				}
			}

			.textareaField {
				.u-form-item__body__right__content__slot {
					display: flex;
					flex-direction: column;
				}
			}

			.hasBtn {
				.u-form-item__body__right__content__slot {

					// display: flex;
					// flex-direction: row;
					>.u-input--square {
						width: 50%;
					}

					.getcode {
						margin-left: 10px;
						width: 160rpx;
					}
					.u-button--small {
						font-size: 24rpx;
					}
				}
			}

			.getAddress {
				padding: 0 10rpx;
			}
		}

		.gap {
			color: #999999;
			text-indent: 10px;
			margin: 10rpx 0;
			font-size: 28rpx;

			&.line {
				border-bottom: 1px solid #999999;
			}

			&.dashed {
				border-bottom: 1px dashed #999999;
			}
		}

		.text-area-label {
			font-size: 28rpx;
			line-height: 60rpx;
			color: #303133;
			margin: -10rpx 0 0 -2rpx;
			position: relative;

			.require {
				font-size: 20px;
				color: #f56c6c;
				position: absolute;
				left: -16rpx;
				top: 5rpx;
			}

			.subLabel {
				font-size: 20rpx;
			}
		}

	}
	.options {
    display: flex;
    margin-left: auto;
    flex-wrap: wrap;
    .option {
        color: #fff;
        min-width: 60rpx;
        text-align: center;
        background: #afabab;
        padding: 4rpx 10rpx;
        border-radius: 16rpx;
        margin-right: 10rpx;
        margin-bottom: 6rpx;
        font-size: 24rpx;
        &.active {
            background: #2788f3;
        }
    }
}
</style>
